package com.sservice.service.service.impl;

import com.sservice.model.dao.*;
import com.sservice.model.entity.*;
import com.sservice.model.vo.InvoicePaperVo;
import com.sservice.service.service.InvoicePaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by suweiming on 2017/12/20.
 */

@Component
public class InvoicePaperServiceImpl implements InvoicePaperService {

    @Autowired
    private ILadingBillDao lbMapper;
    @Autowired
    private LadingOrderMapper loMapper;
    @Autowired
    private InvoicePaperMapper ipMapper;
    @Autowired
    private PurchaseOrderBillMapper purchaseOrderBillMapper;
    @Autowired
    private InvoicePaperBillMapper invoicePaperBillMapper;
    @Autowired
    private IClienteleDao iClienteleDao;


    /**
     * 开票
     *
     * @param arv
     * @return
     */
    @Override
    public Object open(InvoicePaper arv) {
        LadingOrder lo1 = loMapper.selectByPrimaryKey(Integer.valueOf(arv.getOrderId()));
        LadingBill lb = lbMapper.selectByPrimaryKey(Integer.valueOf(lo1.getLadingId()));
        arv.setClienteleId(lb.getClienteleId());
        arv.setPrice(lo1.getPrice().doubleValue()); // 开票单价
        arv.setTransferId(arv.getCreator()); //
        int service_res = ipMapper.insertSelective(arv);
        if (service_res > 0) {
            LadingOrder lo = new LadingOrder();
            lo.setId(Integer.valueOf(arv.getOrderId()));
            if (lo1.getPaperedNumber().compareTo(BigDecimal.valueOf(0.0)) == 0) {
                lo.setPaperStatus("2"); // 部分收票
            }
            lo.setPaperedNumber(lo1.getPaperedNumber().add(BigDecimal.valueOf(arv.getNumber())));
            if (lo.getPaperedNumber().compareTo(lo1.getActual()) == 0) {
                lo.setPaperStatus("3"); // 完全收票
            }
            loMapper.updateByPrimaryKeySelective(lo);
        } else {
            throw new RuntimeException("开票失败");
        }
        return null;
    }

    /**
     * 根据申请单类型和申请单 Id 删除已开票
     *
     * @param arv.orderId 对应订单ID,
     *                    arv.orderType 发票类型
     * @return
     */
    @Override
    public Object delete(InvoicePaper arv) {

        List<InvoicePaperVo> list = ipMapper.selectBy(arv);
        for (InvoicePaperVo ipv : list) {
            if ("0".equals(arv.getOrderType())) { // 删除已开发票
                LadingOrder lo1 = loMapper.selectByPrimaryKey(Integer.valueOf(arv.getOrderId()));
                LadingOrder lo = new LadingOrder();
                lo.setId(lo1.getId());
                lo.setPaperedNumber(lo1.getPaperedNumber().subtract(BigDecimal.valueOf(ipv.getNumber())));
                if (lo.getActual() == null)
                    lo.setActual(BigDecimal.ZERO);
                if (lo.getPaperedNumber().compareTo(BigDecimal.ZERO) == -1) {
                    throw new RuntimeException("数据错误，无法删除！");
                }
                if (lo.getPaperedNumber().compareTo(BigDecimal.ZERO) == 0) {
                    lo.setPaperStatus("1");
                } else if (lo.getPaperedNumber().compareTo(lo.getActual()) == -1) {
                    lo.setPaperStatus("2"); // 部分收票
                } else if (lo.getPaperedNumber().compareTo(lo.getActual()) == 0) {
                    lo.setPaperStatus("3"); // 完全收票
                } else if (lo.getPaperedNumber().compareTo(lo.getActual()) == 1) {
                    throw new RuntimeException("数据错误，无法删除！");
                }
                loMapper.updateByPrimaryKeySelective(lo);
            } else if ("1".equals(arv.getOrderType())) { // 删除已收票明细
                PurchaseOrderBill lo1 = purchaseOrderBillMapper.selectByPrimaryKey(Integer.valueOf(arv.getOrderId()));
                PurchaseOrderBill lo = new PurchaseOrderBill();
                lo.setId(lo1.getId());
                lo.setNumberPapered(lo1.getNumberPapered().subtract(BigDecimal.valueOf(ipv.getNumber())));
                if (lo.getNumberPapered().compareTo(BigDecimal.ZERO) == -1) {
                    throw new RuntimeException("数据错误，无法删除！");
                }
                if (lo.getNumberPapered().compareTo(BigDecimal.ZERO) == 0) {
                    lo.setPaperStatus("1");
                } else if (lo.getNumberPapered().compareTo(lo.getNumberReceive()) == -1) {
                    lo.setPaperStatus("2"); // 部分收票
                } else if (lo.getNumberPapered().compareTo(lo.getNumberReceive()) == 0) {
                    lo.setPaperStatus("3"); // 完全收票
                } else if (lo.getNumberPapered().compareTo(lo.getNumberReceive()) == 1) {
                    throw new RuntimeException("数据错误，无法删除！");
                }
                purchaseOrderBillMapper.updateByPrimaryKeySelective(lo);
            }
            ipMapper.deleteByPrimaryKey(ipv.getId());
        }

        return null;
    }

    /**
     * 根据发票ID删除发票
     *
     * @param arv
     * @return
     */
    public Object deleteBy(InvoicePaper arv) {

        InvoicePaper ip = ipMapper.selectByPrimaryKey(arv.getId()); // 删除发票

        InvoicePaperBill ipb = new InvoicePaperBill();
        ipb.setInvoicePaperId(String.valueOf(ip.getId()));
        List<InvoicePaperBill> list = invoicePaperBillMapper.selectBy(ipb);
        for (InvoicePaperBill ipb1 : list) {
            if ("0".equals(ip.getOrderType())) { // 删除已开发票
                LadingOrder lo1 = loMapper.selectByPrimaryKey(Integer.valueOf(ipb1.getLadingOrderId()));
                LadingOrder lo = new LadingOrder();
                lo.setId(lo1.getId());
                lo.setPaperedNumber(lo1.getPaperedNumber().subtract(ipb1.getNumber()));
                if (lo1.getActual() == null)
                    lo.setActual(lo1.getActual());
                if (lo.getPaperedNumber().compareTo(BigDecimal.ZERO) == -1) {
                    throw new RuntimeException("数据错误，无法删除！");
                }
                if (lo.getPaperedNumber().compareTo(BigDecimal.ZERO) == 0) {
                    lo.setPaperStatus("1");
                } else if (lo.getPaperedNumber().compareTo(lo1.getActual()) == -1) {
                    lo.setPaperStatus("2"); // 部分收票
                } else if (lo.getPaperedNumber().compareTo(lo1.getActual()) == 0) {
                    lo.setPaperStatus("3"); // 完全收票
                } else if (lo.getPaperedNumber().compareTo(lo1.getActual()) == 1) {
                    throw new RuntimeException("数据错误，无法删除！");
                }

                loMapper.updateByPrimaryKeySelective(lo);
            } else if ("1".equals(ip.getOrderType())) { // 删除已收票明细
                PurchaseOrderBill lo1 = purchaseOrderBillMapper.selectByPrimaryKey(Integer.valueOf(ipb1.getLadingOrderId()));
                PurchaseOrderBill lo = new PurchaseOrderBill();
                lo.setId(lo1.getId());
                lo.setNumberPapered(lo1.getNumberPapered().subtract(ipb1.getNumber()));
                if (lo.getNumberPapered().compareTo(BigDecimal.ZERO) == -1) {
                    throw new RuntimeException("数据错误，无法删除！");
                }
                if(lo1.getNumberReceive()==null)
                    lo1.setNumberReceive(BigDecimal.ZERO);
                if (lo.getNumberPapered().compareTo(BigDecimal.ZERO) == 0) {
                    lo.setPaperStatus("1");
                } else if (lo.getNumberPapered().compareTo(lo1.getNumberReceive()) == -1) {
                    lo.setPaperStatus("2"); // 部分收票
                } else if (lo.getNumberPapered().compareTo(lo1.getNumberReceive()) == 0) {
                    lo.setPaperStatus("3"); // 完全收票
                } else if (lo.getNumberPapered().compareTo(lo1.getNumberReceive()) == 1) {
                    throw new RuntimeException("数据错误，无法删除！");
                }
                purchaseOrderBillMapper.updateByPrimaryKeySelective(lo);
            }
            invoicePaperBillMapper.deleteByPrimaryKey(ipb1.getId()); // 删除
        }
        ipMapper.deleteByPrimaryKey(arv.getId()); // 删除
        return null;
    }

    /**
     * 合并开票
     *
     * @param arv.clenteleId,orderId,numbers,no
     * @return f
     */
    @Transactional
    @Override
    public Object combineOpen(InvoicePaperVo arv) {
        String[] orderIds = arv.getOrderId().split(","); // 发货单匹配订单ID
        String[] numbers = arv.getNumbers().split(","); // 发货单匹配订单ID
        BigDecimal total = BigDecimal.ZERO;//  发票总金额
        BigDecimal totalNum = BigDecimal.ZERO;//
        List<InvoicePaperBill> ipbList = new ArrayList<InvoicePaperBill>();
        LadingBill loTmp = null;
        for (int i = 0; i < orderIds.length; i++) {
            LadingOrder lo1 = loMapper.selectByPrimaryKey(Integer.valueOf(orderIds[i]));
            if (i == 0) {
                loTmp = lbMapper.selectByPrimaryKey(Integer.valueOf(lo1.getLadingId()));
            }
            BigDecimal num = BigDecimal.valueOf(Double.valueOf(numbers[i])); //
            total = total.add(num.multiply(lo1.getPrice()));//
            totalNum = totalNum.add(num);//
            lo1.setPaperedNumber(lo1.getPaperedNumber().add(num));
            int compare = lo1.getActual().compareTo(lo1.getPaperedNumber());
            if (num.compareTo(BigDecimal.ZERO) == -1) {
                throw new RuntimeException("数据错误");
            }
            if (compare == -1) {
                throw new RuntimeException("数据错误");
            } else if (compare == 0) {
                lo1.setPaperStatus("3");
            } else if (compare == 1) {
                lo1.setPaperStatus("2"); // 部分收票
            }
            loMapper.updateByPrimaryKeySelective(lo1);
            InvoicePaperBill ipb = new InvoicePaperBill();
            ipb.setLadingOrderId(String.valueOf(lo1.getId()));
            ipb.setNumber(num);
            ipb.setPrice(lo1.getPrice());
            ipb.setGoodsId(loTmp.getGoodsId());
            ipb.setGoodsName(loTmp.getGoodsName());
            ipbList.add(ipb);
        }
        InvoicePaper ip = new InvoicePaper(); // 发票
        ip.setClienteleId(loTmp.getClienteleId()); // 客户Id
        ip.setNumber(totalNum.doubleValue());
        ip.setOrderType("0"); // 开票
        ip.setType("0");//
        ip.setClienteleName(loTmp.getClienteleName());
        ip.setUnitCode(loTmp.getUnitCode());
        ip.setNo(arv.getNo());
        ip.setCreator(arv.getCreator());
        ip.setRemark(arv.getRemark());
        ip.setTotal(total.doubleValue()); // 总金额
        ip.setNumber(totalNum.doubleValue()); // 总数量
        ip.setTransferId(arv.getCreator()); //
        ip.setTransfer(arv.getTransfer());
        ipMapper.insertSelective(ip);
        for (InvoicePaperBill ipb1 : ipbList) {
            ipb1.setInvoicePaperId(String.valueOf(ip.getId()));
            invoicePaperBillMapper.insertSelective(ipb1);
        }
        return null;
    }

    /**
     * 合并收票
     *
     * @param arv
     * @return
     */
    @Transactional
    @Override
    public Object combineReceive(InvoicePaperVo arv) {
        String[] orderIds = arv.getOrderId().split(","); // 收货单匹配订单ID
        String[] numbers = arv.getNumbers().split(","); // 收货单匹配订单ID
        BigDecimal total = BigDecimal.ZERO;//  发票总金额
        BigDecimal totalNum = BigDecimal.ZERO;//
        List<PurchaseOrderBill> list = new ArrayList<PurchaseOrderBill>();
        List<InvoicePaperBill> ipbList = new ArrayList<InvoicePaperBill>();
        PurchaseOrderBill pobTmp = null;
        for (int i = 0; i < orderIds.length; i++) {
            PurchaseOrderBill lo1 = purchaseOrderBillMapper.selectByPrimaryKey(Integer.valueOf(orderIds[i]));
            if (i == 0) pobTmp = lo1;
            BigDecimal num = BigDecimal.valueOf(Double.valueOf(numbers[i])); //
            total = total.add(num.multiply(lo1.getPrice()));//
            totalNum = totalNum.add(num);//
            if (lo1.getNumberPapered() == null) lo1.setNumberPapered(BigDecimal.ZERO);
            lo1.setNumberPapered(lo1.getNumberPapered().add(num));
            int compare = lo1.getNumberReceive().compareTo(lo1.getNumberPapered());
            if (num.compareTo(BigDecimal.ZERO) == -1) {
                throw new RuntimeException("数据错误");
            }
            if (compare == -1) {
                throw new RuntimeException("数据错误");
            } else if (compare == 0) {
                lo1.setPaperStatus("3"); ///'发票申请状态0 未申请1申请中2已申请完毕',
            } else if (compare == 1) {
                lo1.setPaperStatus("2"); // 部分收票
            }
            purchaseOrderBillMapper.updateByPrimaryKeySelective(lo1);
            list.add(lo1);
            InvoicePaperBill ipb = new InvoicePaperBill();
            ipb.setLadingOrderId(String.valueOf(lo1.getId())); // 关联申请单号
            ipb.setNumber(num);
            ipb.setGoodsId(lo1.getGoodsId());//
            ipb.setGoodsName(lo1.getGoodsName());
            ipb.setPrice(lo1.getPrice());
            ipbList.add(ipb);
        }
        InvoicePaper ip = new InvoicePaper(); // 发票
        ip.setClienteleId(String.valueOf(pobTmp.getClienteleId())); //
        ip.setNumber(totalNum.doubleValue()); // 发票数量
        ip.setOrderType("1"); // 收票
        ip.setClienteleName(pobTmp.getClienteleName());
        ip.setUnitCode(pobTmp.getUnitCode());
        ip.setType("1");//
        ip.setNo(arv.getNo());
        ip.setCreator(arv.getCreator());
        ip.setRemark(arv.getRemark());
        ip.setTotal(total.doubleValue()); // 总金额
        ip.setNumber(totalNum.doubleValue()); // 总数量
        ip.setTransferId(arv.getCreator()); //
        ip.setTransfer(arv.getTransfer());
        ipMapper.insertSelective(ip);
        for (InvoicePaperBill ipb1 : ipbList) {
            ipb1.setInvoicePaperId(String.valueOf(ip.getId()));
            invoicePaperBillMapper.insertSelective(ipb1);
        }
        return null;
    }
}
